/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.facade.settlement;

import com.xtd.facade.AbstractFacade;
import com.xtd.model.settlement.Posting;
import com.xtd.util.DateTimeUtil;
import com.xtd.util.FormTypeEnum;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;

/**
 *
 * @author Lu Yuanbin
 */
@Stateless
public class PostingFacade extends AbstractFacade<Posting> {

    public PostingFacade() {
        super(Posting.class);
    }

    public void update(Posting posting) {
        if (posting.getId() == null) {
            create(posting);
        } else {
            edit(posting);
        }
    }

    public List findTodayPostings() {
        return getEntityManager().createQuery("select o from Posting as o where o.createdTime between :startDate and :endDate").setParameter("startDate", DateTimeUtil.getTodayStart()).setParameter("endDate", DateTimeUtil.getTodayEnd()).getResultList();
    }

    public List findByNumber(String number, FormTypeEnum formType, Date date) {
        if (number == null) {
            number = "";
        }
        System.out.println("-------------------"+ date);
        Date startDate = null;
        Date endDate = null;
        if (date == null) {
            startDate = DateTimeUtil.getMonthStart();
            endDate = new Date();
        } else {
            startDate = DateTimeUtil.getDateStart(date);
            endDate = DateTimeUtil.getDateEnd(date);
            System.out.println(date + "  " + startDate + " " + endDate);
        }
        if (formType == null) {
            return getEntityManager().createQuery("select o from Posting as o where o.form.number like :number and  o.createdTime between :startDate and :endDate").setParameter("startDate", startDate).setParameter("endDate", endDate).setParameter("number", "%" + number + "%").getResultList();
        }

        return getEntityManager().createQuery("select o from Posting as o where o.form.number like :number and o.form.type = :type and  o.createdTime between :startDate and :endDate").setParameter("startDate", startDate).setParameter("endDate", endDate).setParameter("number", "%" + number + "%").setParameter("type", formType).getResultList();
    }

    public List findByType(FormTypeEnum formType, Date date) {
        Date startDate = null;
        Date endDate = null;
        if (date == null) {
            startDate = DateTimeUtil.getMonthStart();
            endDate = new Date();
        } else {
            startDate = DateTimeUtil.getDateStart(date);
            endDate = DateTimeUtil.getDateEnd(date);
        }
        return getEntityManager().createQuery("select o from Posting as o where  o.form.type = :type and  o.createdTime between :startDate and :endDate").setParameter("type", formType).setParameter("startDate", startDate).setParameter("endDate", endDate).getResultList();
    }
}
